package hbasecli.controller;

import hbasecli.exception.HBaseDataAccessException;
import hbasecli.exception.ParamException;
import hbasecli.model.json.JsonResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice(basePackages = {"hbasecli.controller"})
public class ExceptionHandlers {

    private static final Logger log = LoggerFactory.getLogger(ExceptionHandlers.class);

    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(value = {
            MissingServletRequestParameterException.class,
            MethodArgumentTypeMismatchException.class,
            HttpMessageNotReadableException.class
    })
    public JsonResponse<String> handleHttpException(Exception exception) {
        String detail;
        if (exception instanceof MissingServletRequestParameterException) {
            detail = exception.getMessage();
        } else if (exception instanceof MethodArgumentTypeMismatchException) {
            detail = "URL 路径参数类型不匹配";
        } else if (exception instanceof HttpMessageNotReadableException) {
            detail = "请求体中的数据格式不匹配";
        } else {
            detail = "其它请求错误";
        }
        log.error("HTTP 请求异常: ", exception);
        return JsonResponse.of(2, "请求格式错误, " + detail, null);
    }

    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(value = {ParamException.class})
    public JsonResponse<String> handleParamException(ParamException exception) {
        log.error("参数校验异常: ", exception);
        return JsonResponse.of(3, exception.getMsg(), null);
    }

    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(value = {HBaseDataAccessException.class})
    public JsonResponse<String> handleHBaseDataAccessException(HBaseDataAccessException exception) {
        log.error("HBase 数据访问异常: ", exception);
        return JsonResponse.of(4, exception.getMsg(), null);
    }

    @ResponseStatus(code = HttpStatus.OK)
    @ExceptionHandler(value = {RuntimeException.class})
    public JsonResponse<String> handleRuntimeException(RuntimeException exception) {
        log.error("运行时异常: ", exception);
        return JsonResponse.of(5, exception.getMessage(), null);
    }

}
